package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String CART_PRE = "CART:PRE:";

    //查询用户购物车
    public List<Cart> queryCartList(Long userId) {
        String key = CART_PRE + userId;
        //看redis中是否有这个key所对应的数据,没有就跑异常
        if (!redisTemplate.hasKey(key)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到hash,由于是  string 对应  map  形式,所以用boundHashOps,
        //hashMapCart就相当于定位到这个用户订单了,userId --> Map
        BoundHashOperations<String, String, String> hashMapCart = redisTemplate.boundHashOps(key);
        if (hashMapCart == null) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到hashMapCart中所有的value的集合,<String,String, String> 的第三个String
        List<String> hashValues = hashMapCart.values();
        //把josn字符串格式的购物车信息反序列化为对象
        List<Cart> cartList = hashValues.stream()
                .map(cart -> JsonUtils.toBean(cart, Cart.class))
                .collect(Collectors.toList());
        return cartList;
    }

    //在购物车添加商品
    //添加,购物车在redis中的结构 Map<用户id转成的key， Map<skuID， cart对象>>
    public void addCart(Cart cart) {
        //得到当前用户的id转成的key
        String key = CART_PRE + UserHolder.getUserId();

        //也就是如果这个订单存在就修改数量
        //得到当前用户对应的hash
        BoundHashOperations<String, String, String> hashMapCart = redisTemplate.boundHashOps(key);
        //得到hashKey
        String hashMapKey = cart.getSkuId().toString();
        Boolean boo = hashMapCart.hasKey(hashMapKey);
        if (boo != null && boo) {
            //得到购物车中当前skuId对应的购物车对象信息
            Cart hashCart = JsonUtils.toBean(hashMapCart.get(hashMapKey), Cart.class);
            //修改当前购物车对象的数量
            cart.setNum(hashCart.getNum() + cart.getNum());
        }
        //直接添加购物车
        hashMapCart.put(hashMapKey, JsonUtils.toString(cart));
    }

    //将本地缓存的购物车单,存到用户购物车中
    public void addCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            addCart(cart);
        }
    }

    //修改购物车信息
    public void updateNum(Long id, Integer num) {
        //得到当前用户的id转成的key
        String key = CART_PRE + UserHolder.getUserId();
        String hashMapKey = id.toString();
        //得到当前用户对应的hash
        BoundHashOperations<String, String, String> hashMapCart = redisTemplate.boundHashOps(key);
        Boolean boo = hashMapCart.hasKey(hashMapKey);
        if (boo == null || !boo) {
            log.error("购物车商品不存在，用户：{}, 商品：{}", key, hashMapKey);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        //获取需要修改的商品
        Cart cart = JsonUtils.toBean(hashMapCart.get(hashMapKey), Cart.class);
        cart.setNum(num);
        //直接添加购物车
        hashMapCart.put(hashMapKey, JsonUtils.toString(cart));
    }

    //删除购物车信息
    public void deleteCart(Long skuId) {
        //得到当前用户的id转成的key
        String key = CART_PRE + UserHolder.getUserId();
        String hashMapKey = skuId.toString();

        //删除
        redisTemplate.opsForHash().delete(key, hashMapKey);
    }
}
